package com.augmentum.oes.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.augmentum.oes.Constants;
import com.augmentum.oes.exception.ParameterException;
import com.augmentum.oes.exception.ServiceException;
import com.augmentum.oes.model.Pagination;
import com.augmentum.oes.model.Question;
import com.augmentum.oes.service.QuestionService;
import com.augmentum.oes.util.PropertyUtil;
import com.augmentum.oes.util.StringUtil;
import com.augmentum.oes.viewmodel.QuestionListModel;

@Controller
@RequestMapping(value = Constants.APP_URL_PREFIX)
public class QuestionController extends BaseController {
    private static final String CREATE_QUESTION_JSP = "question/create-question";
    private static final String CONTENT_ADMIN_JSP = "contentadmin";
    private static final String QUESTION_LIST_PAGE = "questionlist";
    private static final String QUESTION_DETAIL_PAGE = "questiondetail";
    private static final String EDIT_QUESTION_JSP = "question/edit-question";
    private static final String VIEW_USER_DETAIL = "question/view-detail";

    private static final String CREATE_SUCCESS = "Create success!";
    private static final String RIGHT_PAGE_NUMBER = "Please input a right page number!";
    private static final String DELETE_SUCCESS = "Delete success!";
    private static final String EDIT_SUCCESS = "Edit success!";
    private static final String CURRENT_PAGE = "1";
    private static final String QUESTION = "lastquestion";
    private static final String QUESTION_OBJECT = "question";
    private static final String RADIO = "radio";
    private static final String KEYWORD = "keyWord";
    private static final String CURRENTPAGE = "currentPage";
    private static final String SORTSTATUS = "sortstatus";
    private static final String PAGESIZE = "pageSize";
    private static final String PAGNATION = "pagnation";
    private static final String QID = "qid";
    private static final String QUESTION_JSON_LIST = "question/question-list-by-json";

    @Resource
    private QuestionService questionService;

    public void setQuestionService(QuestionService questionService) {
        this.questionService = questionService;
    }

    public QuestionController() {
        super();
    }

    @RequestMapping(value = { "tojsonlist" })
    public ModelAndView toJsonList(@RequestParam(value = "currentPage", required = false) String currentPage,
            @RequestParam(value = "sort", required = false, defaultValue = "ASC") String sort,
            @RequestParam(value = "pageSize", required = false) String pageSize,
            @RequestParam(value = "keyWord", required = false) String keyWord, HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        this.addSession(KEYWORD, keyWord);
        if (!StringUtil.isEmpty(currentPage) || !StringUtil.isEmpty(sort) || !StringUtil.isEmpty(pageSize)) {
            this.addSession(CURRENTPAGE, currentPage);
            this.addSession(SORTSTATUS, sort);
            this.addSession(PAGESIZE, pageSize);
        }
        if (StringUtil.isEmpty(currentPage)) {
            if (!StringUtil.isEmpty((String) session.getAttribute(CURRENT_PAGE))) {
                currentPage = (String) session.getAttribute(CURRENT_PAGE);
            } else {
                currentPage = CURRENT_PAGE;
            }
        }
        if (StringUtil.isEmpty(pageSize)) {
            if (!StringUtil.isEmpty((String) session.getAttribute(PAGESIZE))) {
                pageSize = (String) session.getAttribute(PAGESIZE);
            } else {
                pageSize = PropertyUtil.getProperties(Constants.PAGINATION_PAGESIZE);
            }
        }
        Pagination pagination = new Pagination();
        try {
            pagination.setCurrentPage(Integer.parseInt(currentPage));
            pagination.setPageSize(Integer.parseInt(pageSize));
        } catch (NumberFormatException e) {
            this.addSession(Constants.TIP_MESSAGE, RIGHT_PAGE_NUMBER);
            modelAndView.setViewName(QUESTION_JSON_LIST);
        }
        try {
            this.addSession(Constants.QUESTION_VIEW_LIST, questionService.getAllViewList(pagination, sort, keyWord));
            this.addSession(PAGNATION, pagination);
            modelAndView.setViewName(QUESTION_JSON_LIST);
        } catch (ServiceException e) {
            this.addSession(Constants.TIP_MESSAGE, e.getErrorMessage());
            modelAndView.setViewName(QUESTION_JSON_LIST);
        }
        return modelAndView;
    }

    @RequestMapping(value = { "createquestion" }, method = { RequestMethod.POST })
    public ModelAndView save(@RequestParam(value = "question") String questionStr,
            @RequestParam(value = "answer_radio") String radio, @RequestParam(value = "answer") String[] ansStr) {
        ModelAndView modelAndView = new ModelAndView();
        Question questionInfo = new Question();
        questionStr = questionStr.trim();
        questionInfo.setQuestion(questionStr);
        try {
            questionInfo.setAnswerA(ansStr[0]);
            questionInfo.setAnswerB(ansStr[1]);
            questionInfo.setAnswerC(ansStr[2]);
            questionInfo.setAnswerD(ansStr[3]);
            questionInfo.setCreator(this.getUserId());
            this.addSession(QUESTION_OBJECT, questionInfo);
            this.addSession(RADIO, radio);
            Question question = questionService.createQuestion(questionInfo, radio);
            this.removeSession(QUESTION_OBJECT);
            this.removeSession(RADIO);
            this.addSession(Constants._SUCCESS, CREATE_SUCCESS);
            this.addSession(Constants.QUESTION, question);
            modelAndView.setViewName(CREATE_QUESTION_JSP);
        } catch (ParameterException e) {
            this.addSession(Constants.ERROR_MESSAGE, e.getErrorMessage());
            modelAndView.setViewName(CREATE_QUESTION_JSP);
        } catch (ServiceException e) {
            this.addSession(Constants.TIP_MESSAGE, e.getErrorMessage());
            modelAndView.setViewName(CREATE_QUESTION_JSP);
        }
        return modelAndView;
    }

    @RequestMapping(value = { "tocreatequestion" })
    public ModelAndView toSave(HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        this.addSession(QUESTION, questionService.getLastQuestion());
        this.removeSession(Constants.ERROR_MESSAGE);
        this.removeSession(Constants.TIP_MESSAGE);
        modelAndView.setViewName(CREATE_QUESTION_JSP);
        return modelAndView;
    }

    @RequestMapping(value = { "questionlist" })
    public ModelAndView show(@RequestParam(value = "currentPage", required = false) String currentPage,
            @RequestParam(value = "sort", required = false, defaultValue = "ASC") String sort,
            @RequestParam(value = "pageSize", required = false) String pageSize,
            @RequestParam(value = "keyWord", required = false, defaultValue = "") String keyWord, HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        this.addSession(KEYWORD, keyWord);
        if (!StringUtil.isEmpty(currentPage) || !StringUtil.isEmpty(sort) || !StringUtil.isEmpty(pageSize)) {
            this.addSession(CURRENTPAGE, currentPage);
            this.addSession(SORTSTATUS, sort);
            this.addSession(PAGESIZE, pageSize);
        }
        if (StringUtil.isEmpty(currentPage)) {
            if (!StringUtil.isEmpty((String) session.getAttribute(CURRENT_PAGE))) {
                currentPage = (String) session.getAttribute(CURRENT_PAGE);
            } else {
                currentPage = CURRENT_PAGE;
            }
        }
        if (StringUtil.isEmpty(pageSize)) {
            if (!StringUtil.isEmpty((String) session.getAttribute(PAGESIZE))) {
                pageSize = (String) session.getAttribute(PAGESIZE);
            } else {
                pageSize = PropertyUtil.getProperties(Constants.PAGINATION_PAGESIZE);
            }
        }
        Pagination pagination = new Pagination();
        try {
            pagination.setCurrentPage(Integer.parseInt(currentPage));
            pagination.setPageSize(Integer.parseInt(pageSize));
        } catch (NumberFormatException e) {
            this.addSession(Constants.TIP_MESSAGE, RIGHT_PAGE_NUMBER);
            modelAndView.setViewName(CONTENT_ADMIN_JSP);
        }
        try {
            this.addSession(Constants.QUESTION_VIEW_LIST, questionService.getAllViewList(pagination, sort, keyWord));
            this.addSession(PAGNATION, pagination);
            modelAndView.setViewName(CONTENT_ADMIN_JSP);
        } catch (ServiceException e) {
            this.addSession(Constants.TIP_MESSAGE, e.getErrorMessage());
            modelAndView.setViewName(CONTENT_ADMIN_JSP);
        }
        return modelAndView;
    }

    @RequestMapping(value = "editquestion")
    public ModelAndView edit(@RequestParam(value = "qid") String qid,
            @RequestParam(value = "question") String questionStr, @RequestParam(value = "answer_radio") String radio,
            @RequestParam(value = "answer") String[] ansStr) {
        ModelAndView modelAndView = new ModelAndView();
        questionStr = questionStr.trim();
        Question questionInfo = new Question();
        questionInfo.setQuestion(questionStr);
        questionInfo.setId(Integer.parseInt(qid));
        try {
            questionService.updateQuestion(questionInfo, radio, ansStr);
            this.addSession(Constants.SUCCESS_MSG, EDIT_SUCCESS);
            this.addSession(QID, qid);
            modelAndView.setView(new RedirectView(QUESTION_DETAIL_PAGE + "?" + QID + "=" + qid));
        } catch (ParameterException e) {
            this.addSession(Constants.ERROR_MESSAGE, e.getErrorMessage());
            modelAndView.setView(new RedirectView(QUESTION_LIST_PAGE));
        }
        return modelAndView;
    }

    @RequestMapping(value = "toeditquestion")
    public ModelAndView toEdit(@RequestParam(value = "qid") String qid) {
        ModelAndView modelAndView = new ModelAndView();
        try {
            this.addSession(Constants.QUESTION, questionService.getByQuestionId(qid));
            modelAndView.setViewName(EDIT_QUESTION_JSP);
        } catch (ParameterException e) {
            this.addSession(Constants.ERROR_MESSAGE, e.getErrorMessage());
            modelAndView.setView(new RedirectView(QUESTION_LIST_PAGE));
        }
        return modelAndView;
    }

    @RequestMapping(value = "deletequestion")
    public ModelAndView delete(@RequestParam(value = "checkboxOneInput") String[] idStr) {
        ModelAndView modelAndView = new ModelAndView();
        try {
            questionService.dropById(idStr);
            this.addSession(Constants.TIP_MESSAGE, DELETE_SUCCESS);
            modelAndView.setView(new RedirectView(QUESTION_LIST_PAGE));
        } catch (ParameterException e) {
            this.addSession(Constants.ERROR_MESSAGE, e.getErrorMessage());
            modelAndView.setView(new RedirectView(QUESTION_LIST_PAGE));
        }
        return modelAndView;
    }

    @RequestMapping(value = "questiondetail")
    public ModelAndView detail(@RequestParam(value = "qid") String id) {
        ModelAndView modelAndView = new ModelAndView();
        try {
            this.addSession(Constants.QUESTION, questionService.getByQuestionId(id));
            modelAndView.setViewName(VIEW_USER_DETAIL);
        } catch (Exception e) {
            e.printStackTrace();
            this.addSession(Constants.ERROR_MESSAGE, null);
            modelAndView.setView(new RedirectView(QUESTION_LIST_PAGE));
        }
        return modelAndView;
    }

    @RequestMapping(value = { "questionjsonlist" })
    @ResponseBody
    public QuestionListModel getJsonList(@RequestParam(value = "currentPage", required = false) String currentPage,
            @RequestParam(value = "sort", required = false, defaultValue = "ASC") String sort,
            @RequestParam(value = "pageSize", required = false) String pageSize,
            @RequestParam(value = "keyWord", required = false) String keyWord, HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        QuestionListModel questionListModel = new QuestionListModel();
        questionListModel.setKeyWord(keyWord);
        questionListModel.setSort(sort);
        if (!StringUtil.isEmpty(currentPage) || !StringUtil.isEmpty(sort) || !StringUtil.isEmpty(pageSize)) {
            this.addSession(CURRENTPAGE, currentPage);
            this.addSession(SORTSTATUS, sort);
            this.addSession(PAGESIZE, pageSize);
        }
        if (StringUtil.isEmpty(currentPage)) {
            if (!StringUtil.isEmpty((String) session.getAttribute(CURRENT_PAGE))) {
                currentPage = (String) session.getAttribute(CURRENT_PAGE);
            } else {
                currentPage = CURRENT_PAGE;
            }
        }
        if (StringUtil.isEmpty(pageSize)) {
            if (!StringUtil.isEmpty((String) session.getAttribute(PAGESIZE))) {
                pageSize = (String) session.getAttribute(PAGESIZE);
            } else {
                pageSize = PropertyUtil.getProperties(Constants.PAGINATION_PAGESIZE);
            }
        }
        Pagination pagination = new Pagination();
        try {
            pagination.setCurrentPage(Integer.parseInt(currentPage));
            pagination.setPageSize(Integer.parseInt(pageSize));
            questionListModel.setPagination(pagination);
        } catch (NumberFormatException e) {
            this.addSession(Constants.TIP_MESSAGE, RIGHT_PAGE_NUMBER);
            modelAndView.setViewName(CONTENT_ADMIN_JSP);
        }
        List<Question> list = null;
        try {
            list = questionService.getAllViewList(pagination, sort, keyWord);
            questionListModel.setQuestions(list);
            this.addSession(Constants.QUESTION_VIEW_LIST, list);
            this.addSession(PAGNATION, pagination);
            modelAndView.setViewName(CONTENT_ADMIN_JSP);
        } catch (ServiceException e) {
            this.addSession(Constants.TIP_MESSAGE, e.getErrorMessage());
            modelAndView.setViewName(CONTENT_ADMIN_JSP);
        }
        return questionListModel;
    }

    @RequestMapping(value = "deletebyajax")
    @ResponseBody
    public Map<String, Object> deleteByAjax(@RequestParam(value = "checkboxOneInput") String[] idStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            questionService.dropById(idStr);
            map.put(Constants.SUCCESS, true);
        } catch (ParameterException e) {
            map.put(Constants.SUCCESS, false);
            map.put(Constants.ERROR_MESSAGE, e.getErrorMessage());
        }
        return map;
    }

}
